package jsonDemo

import (
	"encoding/json"
	"fmt"
	"github.com/bitly/go-simplejson"
	"io/ioutil"
	"os"
	"util"
)

func StartDemo() {
	//m1()
	m2()
}

func m2() {
	path := "C:/Users/tianyl/AppData/Local/Google/Chrome/User Data/Default/Bookmarks"
	buf, err := ioutil.ReadFile(path)
	util.CheckError(err)
	jsObj, err := simplejson.NewJson(buf)
	util.CheckError(err)
	arr, err := jsObj.Get("roots").Get("bookmark_bar").Get("children").Array()
	util.CheckError(err)
	file, err := os.Create("C:\\Users\\tianyl\\Desktop\\bookmark.txt")
	util.CheckError(err)
	defer file.Close()
	for _, val := range arr {
		//valStr, _ := strconv.Atoi(val.(string))
		//fmt.Println(valStr)
		//fmt.Println(val["name"])
		name := val.(map[string]interface{})["name"]
		if name.(string) == "收藏" {
			arr2 := val.(map[string]interface{})["children"].([]interface{})
			for _, val2 := range arr2 {
				urlType := val2.(map[string]interface{})["type"].(string)
				if urlType == "url" {
					name := val2.(map[string]interface{})["name"].(string)
					url := val2.(map[string]interface{})["url"].(string)
					//fmt.Println(name, url)
					file.WriteString(name + " " + url + "\r\n")
				}
				//fmt.Println(val2.(map[string]interface{})["name"])
			}
			//fmt.Println(arr2)
		}
		//fmt.Println(name)
	}
}

type Grade struct {
	Num      int
	Name     string
	Eclasses []Eclass
}

type GradeSlice struct {
	Grades []Grade
}

type Eclass struct {
	Name  string
	Email string
}

func m1() {
	var str = `{"Grades":[{"Num":1,"Name":"1年级"},{"Num":2,"Name":"2年级"}]}`
	var grades GradeSlice
	//知道json结构
	err := json.Unmarshal([]byte(str), &grades)
	if err != nil {
		fmt.Println(err)
		return
	}
	//json结构未知
	fmt.Println(grades)
	var f interface{}
	err = json.Unmarshal([]byte(str), &f)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(f)
	//生成json
	var grades2 GradeSlice
	grades2.Grades = append(grades2.Grades, Grade{Num: 1, Name: "1年级"})
	grades2.Grades = append(grades2.Grades, Grade{Num: 2, Name: "2年级"})
	b, err := json.Marshal(grades2)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(b))
}
